/**
 * @description: 大屏适配
 * @param {*}
 * @return {*}

 */

import { onMounted, onUnmounted } from 'vue';
import { throttle } from 'lodash'

type Options = {
  targetX?: number,
  targetY?: number,
  targetRatio?: number,
}

export default function useScalePage(options: Options) {
  // 大屏的适配
  function triggerScale() {
    // 1.设计稿的尺寸
    let targetX = options?.targetX || 1920;
    let targetY = options?.targetY || 1080;
    let targetRatio = options.targetRatio || (16 / 9);//宽高比例

    // 2.拿到当前设备（浏览器）的宽度
    let currentX = document.documentElement.clientWidth || document.body.clientWidth
    let currentY = document.documentElement.clientHeight || document.body.clientHeight

    // 3.计算缩放比例
    let scaleRatio = currentX / targetX;// 参照宽度进行缩放（默认情况）
    let currentRatio = currentX / currentY;// 宽高比例

    // 超宽屏 居中
    if (currentRatio > targetRatio) {
      scaleRatio = currentY / targetY;// 参照宽度进行缩放（默认情况）
      // 水平居中
      document.body.style = `width:${targetX}px;height:${targetY}px;transform:scale(${scaleRatio}) translateX(-50%); left:50%;`;
    } else {
      // 4.开始缩放网页
      document.body.style = `width:${targetX}px;height:${targetY}px;transform:scale(${scaleRatio})`
    }
  }

  // 节流
  const resizeFunc = throttle(() => {
    console.log('resize');
    triggerScale();
  }, 100)

  onMounted(() => {
    triggerScale();
    window.addEventListener('resize', resizeFunc);
  })

  onUnmounted(() => {
    window.removeEventListener('resize', resizeFunc);
  })
}
